package com.xiao.gulimall.product.service.impl;

import com.xiao.gulimall.product.dao.AttrGroupDao;
import com.xiao.gulimall.product.dao.CategoryDao;
import com.xiao.gulimall.product.entity.AttrGroupEntity;
import com.xiao.gulimall.product.entity.CategoryEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiao.common.utils.PageUtils;
import com.xiao.common.utils.Query;

import com.xiao.gulimall.product.dao.AttrDao;
import com.xiao.gulimall.product.entity.AttrEntity;
import com.xiao.gulimall.product.service.AttrService;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {


    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Override
    public boolean save(AttrEntity entity) {
        Long catelogId = entity.getCatelogId();
        Long attrGroupId = entity.getAttrGroupId();
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        entity.setCatelogName(categoryEntity.getName());
       if(attrGroupId != null){
           AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
           entity.setGroupName(attrGroupEntity.getAttrGroupName());
       }
        return super.save(entity);
    }

    @Override
    public PageUtils queryPage(String type,Long catId,Map<String, Object> params) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if(catId != null && catId != 0){
            wrapper.eq("catelog_id",catId);
        }
        if("base".equals(type)){
            wrapper.eq("attr_type",1);
        }
        if("sale".equals(type)){
            wrapper.eq("attr_type",0);
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<AttrEntity> attrRelation(Long attrGroupId) {
        return baseMapper.selectList(new QueryWrapper<AttrEntity>().eq("attr_group_id",attrGroupId));
    }

    @Override
    public List<AttrEntity> noAttrRelation() {
        /**
         * 分组的字段不能为空 没有被选择的
         * 当前属性必须是 规格参数 不能是其他的
         */
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.isNull("attr_group_id");
        wrapper.eq("attr_type",1);
        return baseMapper.selectList(wrapper);
    }

}